package pow

import (
	"bytes"
	"day25/block"
	"day25/tools"
	"math/big"
	"strconv"
)

/**
 ** @author: hui
 ** @email: 3231954428@qq.com
 ** @phone: 15779563913
 ** @DataTime: 2022/3/4 10:38
 **/

const BITS = 20

type ProofOfWork struct {
	Block	*block.Block
	Target	*big.Int
}

func CreatePow(block *block.Block) *ProofOfWork{
	//创建大整数变量
	target := big.NewInt(1)
	//参数1：要移的参数 参数2：移几位
	target.Lsh(target, 255-BITS)
	pow := ProofOfWork{
		Block: block,
		Target: target,
	}

	return &pow
}
//计算随机数
func (pow *ProofOfWork)Run() ([]byte, int64){
	var nonce int64
	nonce = 0
	block := pow.Block
	block.Nonce = nonce

	//大整数
	num := big.NewInt(0)

	for {
		//timeByte := []byte(strconv.FormatInt(block.TimeStamp, 10))
		nonceByte := []byte(strconv.FormatInt(block.Nonce, 10))
		hashByte := bytes.Join([][]byte{block.PrevHash, block.Data,  nonceByte}, []byte{})
		hash := tools.SetHash(hashByte)
		num = num.SetBytes(hash)
		if num.Cmp(pow.Target) == -1 {
			return hash, nonce
		}
		nonce ++
	}

	return nil, 0

}